/**
 * 
 */
package abel.wlmr.client;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import abel.util.HexString;
import abel.wlmr.model.WlmrPacket;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * @author Abel
 *
 */
public class WlmrPacketDecoder extends ByteToMessageDecoder {

    private static final Logger log = LoggerFactory.getLogger(WlmrPacketDecoder.class);

    /* (non-Javadoc)
     * @see io.netty.handler.codec.ByteToMessageDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, java.util.List)
     */
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        log.info("Up bytes: {}", HexString.bytesToHexStringWithBlank(in.duplicate()));
        WlmrPacket p = null;

        do {
            p = new WlmrPacket(log);
            p.tryFindHead(in);
            
            int plen = p.parseBuf(in);

            // deal parsing result.
            if (plen > 0) {
                out.add(p);
            } else {
                // break if not whole packet.
                p = null;
            }
        } while (p != null);

        // log.
        String afn = out.isEmpty() ? "" : ((WlmrPacket) out.get(0)).getAfn().toString();
        log.info("Up {} packets [{}...] and left bytes: {}.",
            out.size(), afn, in.readableBytes());
    }

}
